using System.IO;
using System;
using System.Net;

namespace SpoonStun.Message
{
	public class RegisterMessage : IStunMessage
	{
		public enum StatusValue : byte { Ok, Faild }
		public enum TypeValue : byte{Request, Response}

		private int _id = new Random().Next();
		private StatusValue _status = StatusValue.Ok;
		private TypeValue _type = TypeValue.Request;
		private IPEndPoint _globalEndPoint = new IPEndPoint(IPAddress.Any, 0);

		public int MsgId
		{
			get { return 1; }
		}

		public int Id
		{
			get { return _id; }
			set { _id = value; }
		}

		public StatusValue Status
		{
			get { return _status; }
			set { _status = value; }
		}

		public TypeValue Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public IPEndPoint GlobalEndPoint
		{
			get { return _globalEndPoint; }
			set { _globalEndPoint = value; }
		}

		public void SetBytes(byte[] data)
		{
			MemoryStream stream = new MemoryStream(data);
			BinaryReader br = new BinaryReader(stream);

			Id = br.ReadInt32();
			Type = (TypeValue) br.ReadByte();
			Status = (StatusValue)br.ReadByte();
			GlobalEndPoint = new IPEndPoint(new IPAddress(br.ReadBytes(4)), br.ReadInt32());
		}

		public byte[] GetBytes()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			bw.Write(Id);
			bw.Write((byte)Type);
			bw.Write((byte)Status);
			bw.Write(GlobalEndPoint.Address.GetAddressBytes());
			bw.Write(GlobalEndPoint.Port);

			return stream.ToArray();
		}
	}
}